<!-- 换电管理 -->
<template>
  <el-form ref="ruleFormRef" :model="ruleForm" inline class="ruleForm">
    <el-form-item label="所属街道：" prop="deviceCode">
      <el-input
        v-model="ruleForm.queryRo.orgName"
        style="width: 150px"
        clearable
        placeholder="请输入所属街道"
      />
    </el-form-item>
   
    <el-form-item label="绑定状态：" prop="isBinding">
      <el-select v-model="ruleForm.queryRo.isBinding" clearable style="width: 150px">
        <el-option
                    v-for="item in isBindingList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                />
      </el-select>
    </el-form-item>

    <el-form-item label="设备状态：" prop="status">
      <el-select v-model="ruleForm.queryRo.status" clearable style="width: 150px">
        <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.name"
            :value="item.value"
        />
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="search">查 询</el-button>
      <el-button type="success" @click="addDevice()">新增</el-button>
    </el-form-item>
  </el-form>

  <el-table :data="tableList" style="width: 100%" v-loading="loading">
    <el-table-column prop="vehicleNo" label="车牌号" align="center" />
    <el-table-column prop="bmsNo" label="充电设备编号" align="center" />
    <el-table-column prop="operatorId" label="运营商编号" align="center" />
<!--    <el-table-column prop="workerId" label="代充人员或司机" align="center" />-->
    <el-table-column prop="investDate" label="投资时间" align="center" />
    <el-table-column prop="totalMoney" label="总收益" align="center" />
    <el-table-column prop="rate" label="分润比例" align="center" />
    <el-table-column prop="investTotalIncome" label="投资总收入" align="center"/>
    <el-table-column prop="status" label="设备状态" align="center">
      <template #default="scope">
        <span >{{ statusTpye(scope.row.status)}}</span>
      </template>
    </el-table-column>
    <el-table-column prop="operatorPerson" label="分管运营人" align="center" />
    <el-table-column prop="orgName" label="所属街道" align="center"/>
    <el-table-column prop="isBinding" label="绑定状态" align="center">
      <template #default="scope">
        <span >{{ isBindingTpye(scope.row.isBinding)}}</span>
      </template>
    </el-table-column>
    <el-table-column prop="workerTime" label="已工作时长 (h)" align="center" />
    <el-table-column prop="electricity" label="已充电电量 (kwh)" align="center" />
    <el-table-column prop="nowElectricity" label="当前电量 (kwh)" align="center" />
    <el-table-column prop="deviceCapacity" label="设备容量 (kwh)" align="center" />
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button link @click="openDialog(scope.row)" type="primary">查看详情</el-button>
        <el-button link type="primary" size="small" @click="editDevice(scope.row)">编辑</el-button>
        <el-button link type="danger" size="small" @click="delDevice(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <footer class="pagination">
    <el-pagination
      v-model:currentPage="ruleForm.current"
      v-model:page-size="ruleForm.pageSize"
      :page-sizes="[10, 20, 30, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      small
    />
  </footer>

  <el-drawer
      v-model="drawer"
      :title="tableForm.data.id ? '编辑设备资料': '新增设备资料'"
      :direction="direction">
    <el-form
        ref="ruleFormRef"
        :model="tableForm.data"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
    >
<!--      vehicleNo:"",-->
<!--      bmsNo:"",-->
<!--      operatorId: "",-->
<!--      operatorPerson: "",-->
<!--      orgName: "",-->
      <el-form-item label="车牌号" prop="vehicleNo">
        <el-input v-model="tableForm.data.vehicleNo" placeholder="请填车牌号" />
      </el-form-item>
      <el-form-item label="充电设备编号" prop="bmsNo">
        <el-input
            v-model="tableForm.data.bmsNo"
            placeholder="请填充电设备编号"
            maxlength="16"/>
        <div>(设备编号请以-6611-开头,并为16位!!!)</div>
      </el-form-item>
      <el-form-item label="运营商号" prop="operatorId">
        <el-input v-model="tableForm.data.operatorId" placeholder="请填运营商号" />
      </el-form-item>
      <el-form-item label="分管运营人" prop="operatorPerson">
        <el-input v-model="tableForm.data.operatorPerson" placeholder="请填分管运营人" />
      </el-form-item>
      <el-form-item label="所属街道" prop="orgName">
        <el-input v-model="tableForm.data.orgName" placeholder="请填所属街道" />
      </el-form-item>

    </el-form>
    <template #footer>
      <div style="flex: auto">
        <!--        <el-button @click="cancelForm">取消</el-button>-->
        <el-button type="primary"  @click="submitForm(ruleFormRef)">确定</el-button>
      </div>
    </template>
  </el-drawer>

  <EquipmentDetailDialog v-model:show="showDialog"  :detail="detail"></EquipmentDetailDialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import EquipmentDetailDialog from './components/EquipmentDetailDialog.vue'
import api from '@/api/apis/equipmentApi'
import {ElMessage, ElMessageBox, FormInstance, FormRules} from "element-plus";
const ruleForm = reactive({
  queryRo:{
    status:"",
    isBinding:"",
    orgName:"",

  },
  current: 1,
  pageSize: 50,
  searchCount: true
})
const time=ref<any>([])
//总数
const total = ref(0)
//搜索
const search = () => {
  ruleForm.current = 1
  getTableList()
}

const drawer = ref(false)
const ruleFormRef = ref<FormInstance>()

//编辑
const editDevice = (row)=>{
  tableForm.data= {...row}
  // status.value = ruleForm.data.status == 1 ? true : false
  // ruleForm.data.status = 1
  drawer.value = true
  console.log('ruleForm',tableForm.data)
}

const tableForm = reactive({
  data:{
    id:"",
    vehicleNo:"",
    bmsNo:"",
    operatorId: "",
    operatorPerson: "",
    orgName: "",
  },
})


//新增
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let res, message
      // ruleForm.data.sex = sex.value
      console.log('data',tableForm.data)
      if(tableForm.data.id){
        res = await api.updateDevice(tableForm.data)
        message = '编辑成功！'
      }else {
        res = await api.addDevice(tableForm.data)
        message = '新增成功！'
      }
      if(res.data.code == 200){
        ElMessage({
          message: message,
          type: 'success',
        })
        getTableList()
        drawer.value = false
      }
      if(res.data.code == 1001){
        ElMessage({
          message: "设备编号请以6611开头",
          type: 'error',
        })
        getTableList()
        drawer.value = false
      }
      if(res.data.code == 1002){
        ElMessage({
          message: "设备编号应为16位",
          type: 'error',
        })
        getTableList()
        drawer.value = false
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 新增
const addDevice = async (formEl: FormInstance | undefined) => {
  drawer.value = true
  let  obj = {
    vehicleNo:"",
    bmsNo:"",
    operatorId: "",
    operatorPerson: "",
    orgName: "",
  }
  tableForm.data = obj
}

// 必填规则
const rules = reactive<FormRules>({
  vehicleNo: [
    { required: true, message: '请填车牌号', trigger: 'blur' },
  ],
  bmsNo: [
    { required: true, message: '请填充电设备编号', trigger: 'blur' },
  ],
  operatorId: [
    { required: true, message: '请填运营商号', trigger: 'blur' },
  ],
  operatorPerson: [
    { required: true, message: '请填分管运营人', trigger: 'blur' },
  ],
  orgName: [
    { required: true, message: '请填所属街道', trigger: 'blur' },
  ],
  // complaintStatus: [
  //   { required: true, message: '请填结束充电电量', trigger: 'blur' },
  // ],
  // complaintTime: [
  //   { required: true, message: '请填结束充电电量', trigger: 'blur' },
  // ],
})

const delDevice = (row)=>{
  ElMessageBox.confirm(
      '您确定要删除该设备吗?',
      '注意',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        let res = await api.delDeviceById(row.id)
        console.log(res)
        if(res.data.code == 200){
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getTableList()
        }

      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })

}


const isBindingTpye = (value: number) => {
  let obj: any = {
    0: '未绑定',
    1: '已绑定',
  }
  return obj[value]
}

const statusTpye = (value: number) => {
  let obj: any = {
    0: '离线',
    1: '在线',
  }
  return obj[value]
}
const isBindingList =[
  {name:"未绑定",value:0},
  {name:"已绑定",value:1},
]

const statusList =[
  {name:"离线",value:0},
  {name:"在线",value:1},
]


//表格数据
const tableList = ref([])
//加载
const loading = ref(false)
onMounted(()=>{
  getTableList()
})
//获取表格数据
const getTableList = async () => {
  loading.value = true
  try {
    let obj = { ...ruleForm }
    // obj.queryRo.carDeviceOntime =time.value?time.value[0]:undefined
    // obj.queryRo.carDeviceOfftime =time.value?time.value[1]:undefined
    let {data} = await api.equipmentPage(obj)
    tableList.value= data.data.rows
    total.value= Number(data.data.total)

  } catch (error) {
    loading.value = false
  }
  loading.value = false
}
// //改变每页条数
const handleSizeChange = (val: number) => {
  ruleForm.current = 1
  ruleForm.pageSize = val
  getTableList()
}
//改变当前页数
const handleCurrentChange = (val: number) => {
  ruleForm.current = val
  getTableList()
}

//弹框开关
const showDialog = ref(false)
//详情id
const detail = ref()
//打开详情弹框
const openDialog = (val: string) => {
  detail.value = val
  showDialog.value = true
}
</script>

<style scoped lang="scss">
footer {
  display: flex;
  justify-content: center;
  margin-top: 15px;
}
</style>
